//
//  MYHomeViewController.swift
//  swift2.0项目开始
//
//  Created by 龚昕炜 on 16/7/28.
//  Copyright © 2016年 龚昕炜. All rights reserved.
//

import UIKit

private let MYHomeViewControllerCellIdentifier = "MYHomeViewControllerCellIdentifier"

class MYHomeViewController: MYBaseTableViewController {
    
    /** 模型视图 */
    private lazy var homeViewController: MYStatusListViewModel = MYStatusListViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        /** 已登录(tableView) */
        if MYLoginViewModel.shareInstance.isLogin {
            loadData()
            
            /** 注册cell */
            self.tableView.registerClass(MYHomeTableViewCell.self, forCellReuseIdentifier:MYHomeViewControllerCellIdentifier)
            
            /** 预估 */
            self.tableView.estimatedRowHeight = 200
            /** 自动计算行高 */
            self.tableView.rowHeight = UITableViewAutomaticDimension
            /** 上拉刷新指示器 */
            self.tableView.tableFooterView = pullView
            
            /** 添加下拉刷新控件 */
            self.tableView.addSubview(refreshView)
            /** 添加监听事件 */
            refreshView.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
            
        } else {
            /** 未登录(访问者) */
            self.visitor.setUpInfo("visitordiscover_feed_image_house", text: "关注一些人，回这里看看有什么惊喜")
        }
    }
    
    
    
    /** 上拉刷新控件 */
    private lazy var pullView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    /** 下拉刷新控件 */
    private lazy var refreshView: MYRefreshView = MYRefreshView()
    
    /** 正在加载的标识 */
    private var isloading: Bool = false
}

extension MYHomeViewController {
    
    @objc private func loadData() {
        
        SVProgressHUD.show()
        
        var max_id = 0
        /** 下拉刷新 */
        var since_id = homeViewController.list.first?.statusModel?.id ?? 0
        
        /** 上拉刷新 */
        if pullView.isAnimating() {
           max_id  = homeViewController.list.last?.statusModel?.id ?? 0
           /** 上拉刷新时，下拉标志设为默认值 */
           since_id = 0
        }

        /** 加载完成 */
        homeViewController.loadData(since_id, max_id: max_id, success: { () -> () in
            SVProgressHUD.dismiss()
            self.pullView.stopAnimating()
            self.isloading = false
            self.refreshView.endReflashing()
            self.tableView.reloadData()
            }, failed: { () -> () in
                SVProgressHUD.showErrorWithStatus("加载数据失败")
                self.pullView.stopAnimating()
        })
    }
}

// MARK: 数据源方法
extension MYHomeViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        print(homeViewController.list.count)
        return homeViewController.list.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(MYHomeViewControllerCellIdentifier, forIndexPath: indexPath) as! MYHomeTableViewCell
        
        let viewModel = homeViewController.list[indexPath.row]
        
//        if (indexPath.row == homeViewController.list.count - 1) && (isloading == false) {
//            print("=========\(isloading) --- \(homeViewController.list.count - 1)")
//            pullView.startAnimating()
//            isloading = true
//            loadData()
//        }
        
        cell.cellViewModel = viewModel
        
        return cell
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        let row = indexPath.row
        let section = tableView.numberOfSections - 1
        
        if section < 0 || row == 0 {
            return
        }
        
        let count = tableView.numberOfRowsInSection(section)
        
        if row == (count - 1) && !isloading {
            isloading = true
            pullView.startAnimating()
            loadData()
        }
    }
}